<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UserFilled, StarFilled, Lock, Unlock, Search, Avatar, Medal } from '@element-plus/icons-vue'
import { useAdminStore } from '@/stores/admin'

const adminStore = useAdminStore()
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const userList = ref([])
const searchKey = ref('')
const elTableRef = ref(null)

const fetchUsers = async () => {
  try {
    loading.value = true
    const response = await adminStore.getUserList({
      page: currentPage.value,
      pageSize: pageSize.value,
      search: searchKey.value
    })
    userList.value = response.items
    total.value = response.total
  } catch (error) {
    console.error('Failed to fetch users:', error)
    // 使用模拟数据
    userList.value = [
      {
        userID: 1,
        name: '张三',
        email: 'zhangsan@example.com',
        isVIP: 1,
        isFrozen: 0,
        role: [1, 2]
      },
      {
        userID: 2,
        name: '李四',
        email: 'lisi@example.com',
        isVIP: 0,
        isFrozen: 1,
        role: [1]
      }
    ]
    total.value = 2
    ElMessage({
      message: '获取用户列表失败，已显示模拟数据',
      type: 'warning',
      duration: 5 * 1000
    })
  } finally {
    loading.value = false
  }
}

const handleFreeze = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要${user.isFrozen ? '解冻' : '冻结'}该用户吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    if (user.isFrozen) {
      await adminStore.unfreezeUser(user.userID)
      ElMessage.success('解冻成功')
    } else {
      await adminStore.freezeUser(user.userID)
      ElMessage.success('冻结成功')
    }

    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUsers()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchUsers()
}

const handleSearch = () => {
  currentPage.value = 1
  fetchUsers()
}

// 定义 handleResize 函数，以便在 onUnmounted 中正确移除监听器
const handleResize = () => {
  if (elTableRef.value) {
    elTableRef.value.doLayout()
  }
}

onMounted(() => {
  fetchUsers()
  nextTick(() => {
    if (elTableRef.value) {
      elTableRef.value.doLayout()
    }
  })

  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <div class="user-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span style="font-size: 20px; font-weight: bold; display: flex; align-items: center; white-space: nowrap; flex-grow: 1; flex-shrink: 0;" >
            <el-icon style="margin-right: 8px; color: #1976d2"><UserFilled /></el-icon>
            用户管理
          </span>
          <div class="search-bar">
            <el-input
              v-model="searchKey"
              placeholder="搜索用户名/邮箱"
              clearable
              @keyup.enter="handleSearch"
              style="flex: 1; max-width: 220px; margin-right: 8px;"
            />
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="userList"
        style="width: 100%"
        border
        empty-text="暂无用户数据"
        ref="elTableRef"
        table-layout="fixed"
      >
        <el-table-column label="头像" width="70">
          <template #default="{ row }">
            <el-avatar :icon="Avatar" :size="36" style="background: #e3eafc; color: #1976d2;" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="用户名" flex="1">
          <template #default="{ row }">
            <span style="display: flex; align-items: center;">
              <el-icon v-if="row.isVIP" style="color: #f7b500; margin-right: 4px;"><StarFilled /></el-icon>
              {{ row.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" flex="1" />
        <el-table-column prop="isVIP" label="会员" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.isVIP" type="warning">VIP</el-tag>
            <el-tag v-else type="info">普通</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isFrozen" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isFrozen ? 'danger' : 'success'">
              <el-icon style="vertical-align: middle; margin-right: 2px;">
                <Lock v-if="row.isFrozen" />
                <Unlock v-else />
              </el-icon>
              {{ row.isFrozen ? '已冻结' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" flex="1">
          <template #default="{ row }">
            <el-tag v-for="r in row.role" :key="r" :type="r === 1 ? 'info' : r === 2 ? 'primary' : r === 3 ? 'success' : 'warning'" style="margin-right: 4px;">
              <el-icon style="vertical-align: middle; margin-right: 2px;">
                <Medal />
              </el-icon>
              {{ r === 1 ? '普通用户' : r === 2 ? '课程管理员' : r === 3 ? '系统管理员' : '公司领导' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template #default="{ row }">
            <el-button
              :type="row.isFrozen ? 'success' : 'danger'"
              size="small"
              :icon="row.isFrozen ? Unlock : Lock"
              @click="handleFreeze(row)"
            >
              {{ row.isFrozen ? '解冻' : '冻结' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.user-management {
  padding: 0;
  width: 100%;
}

.el-card {
  width: 100% !important;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.04);
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  padding-bottom: 8px;
  flex-wrap: wrap;
}

.search-bar {
  display: flex;
  align-items: center;
  flex-shrink: 0;
  min-width: 200px;
  margin-left: auto;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.el-table th {
  background: #f5f7fa;
  color: #34495e;
  font-weight: bold;
}

.el-table .el-tag {
  font-size: 13px;
}
</style> 